import 'dart:async';


import 'package:chewie/chewie.dart';
import 'package:chewie/src/material/material_progress_bar.dart';
import 'package:flutter/material.dart';
import 'package:robotcontrol/utils/format_duration_util.dart';
import 'package:robotcontrol/utils/toast.dart';
import 'package:video_player/video_player.dart';

class VideoControlsWidget extends StatefulWidget{
  final  bool showLoadingOnInitialize ;//是否显示加载动画
  final bool showBigPlayIcon;//是否显示全屏播放按钮
  final Widget overlayUI;//浮层ui
  final Gradient bottomGradient;//底层控制栏的背景色：一般为渐变色
  const VideoControlsWidget({Key key,this.showLoadingOnInitialize = true,
    this.showBigPlayIcon = false ,this.overlayUI,this.bottomGradient}):super(key:key);
  _VideoControlsState createState()=> _VideoControlsState();

}
// SingleTickerProviderStateMixin:ticker,定义 AnimationController 需要
class _VideoControlsState extends State<VideoControlsWidget> with SingleTickerProviderStateMixin{
  VideoPlayerValue _lastValue;//视频播放数据，播放位置，缓存状态，错误状态，设置
  double _lastVolume;//声音大小
  bool _hideStuff=true;//
  Timer _hideTimer;//控制栏隐藏时间计时器
  Timer _initTmer;
  Timer _showAfterExpandCollapseTimer;//全屏切换Timer
  bool _dragging = false;
  bool _displayTapped =false;
  final barHeight = 48.0;//底部控制栏的高度
  final marginSize = 5.0;
  VideoPlayerController controller;//视频播放控制器
  ChewieController chewieController;
  AnimationController playPauseIconAnimationController; //播放暂停图标动画控制器

  @override
  void dispose() {
    _dispose();
    super.dispose();
  }
  _dispose(){
    controller.removeListener(_updateState);
    _hideTimer?.cancel();
    _initTmer?.cancel();
    _showAfterExpandCollapseTimer?.cancel();
  }
  /// 更新状态：重新获取视频播放的状态数据
  _updateState(){
    setState((){
      _lastValue = controller.value;
    });
  }


  @override
  void didChangeDependencies() {
    final _oldController = chewieController;
    chewieController = ChewieController.of(context);
    controller = chewieController.videoPlayerController;
    // vsync:ticker 驱动动画,每次屏幕刷新都会调用TickerCallback，
    // 一般 SingleTickerProviderStateMixin 添加到 State，直接使用this
    playPauseIconAnimationController = AnimationController(vsync: this,
    duration: const Duration(milliseconds: 400),
    reverseDuration: const Duration(milliseconds: 400));
    if(_oldController != chewieController){
      _dispose();
      _initialize();
    }
    super.didChangeDependencies();
  }
  //初始化
  _initialize() async{
    controller.addListener(_updateState);
    //重新获取视频播放状态数据
    _updateState();
    if((controller.value != null && controller.value.isPlaying) || chewieController.autoPlay){
    _startHideTimer();
    }
    if(chewieController.showControlsOnInitialize){
      _initTmer = Timer(const Duration(milliseconds: 200),(){
        setState((){
          _hideStuff = false;
        });
      });
    }
  }
  @override
  Widget build(BuildContext context) {
    if(_lastValue.hasError){
      return chewieController.errorBuilder != null
          ? chewieController.errorBuilder(context,chewieController.videoPlayerController.value.errorDescription)
          : const Center(child: Icon(Icons.error,color: Colors.white,size: 42,));
    }
    return _playVideo();
  }
//播放器
  _playVideo(){
    return GestureDetector(
      onTap: ()=> _cancelAndREstartTimer(),
      child: AbsorbPointer(
        absorbing: true,//absorbing true 不响应事件
        child: Stack(
          children: [
            Column(
              children: [
                // 不是正在播放 && duration == null || 正在缓冲
                if(_lastValue != null &&
                      !_lastValue.isPlaying &&
                        _lastValue.duration == null ||
                          _lastValue.isBuffering
                )
                  Expanded(child: Center(child: _loadingIndicator(),))
                else
                  _buildHitArea(),///创建点击区域
                ///底部控制栏
                _buildBottomBar(context)
              ],
            ),
            //浮层
            _overlayUI()
          ],
        ),
      ),//禁止用户输入的控件 会消耗事件 跟IgnorePointer（不消耗事件）类似
    );
  }
  //浮层
  _overlayUI(){
    return widget.overlayUI != null ?
    AnimatedOpacity(opacity: _hideStuff?0.0:1.0, duration: Duration(milliseconds: 300),
    child: widget.overlayUI,):
    Container(child: Center(child: Text("我曹没有悬浮了"),),);
  }
  //取消并重新开始计时 隐藏时间
  void _cancelAndREstartTimer(){
    _hideTimer?.cancel();
    _startHideTimer();
    setState((){
      _hideStuff = false;
      _displayTapped = true;
    });
  }
  void _startHideTimer(){
    _hideTimer =Timer(const Duration(seconds: 3), () {
      setState((){
        _hideStuff = true;
      });
    });
  }
  //中间进度条
  _loadingIndicator(){
    //初始化是否显示进度
    return widget.showLoadingOnInitialize?CircularProgressIndicator():null;
  }
  /// 视频点击区
  Expanded _buildHitArea(){
    //视频是否播放完毕 当前位置》=持续时间
    final bool isFinished = _lastValue.position >= _lastValue.duration;
    return Expanded(child: GestureDetector(
      onTap: (){
        //显示隐藏控制栏
        if(_lastValue != null && _lastValue.isPlaying){
          if(_displayTapped){
            setState((){
              _hideStuff = true;
            });
          }else{
            _cancelAndREstartTimer();
          }
        }else{
          setState((){
            _hideStuff = true;
          });
        }
      },
      //中间大按钮
      child: Container(
        color: Colors.transparent,
        child: Center(
          // AnimatedOpacity:使子组件变的透明
          child: AnimatedOpacity(
            opacity: _lastValue != null && !_lastValue.isPlaying && !_dragging?1.0:0.0,
            duration: const Duration(milliseconds: 300),//动画执行时间
            child: widget.showBigPlayIcon?
                  _playPauseButton(isFinished)
            :Container(),
          ),
        ),
      ),
    ));//weight
  }
  //播放 暂停 重播按钮
  Widget _playPauseButton(isFinished){
    //手势
    return GestureDetector(
            child: Container(
              decoration: BoxDecoration(
                color: Theme.of(context).dialogBackgroundColor,
                borderRadius: BorderRadius.circular(48.0)
              ),
              child: Padding(
                padding: const EdgeInsets.all(12.0),
                child: Material(
                  child: IconButton(
                    icon: isFinished?
                    const Icon(Icons.replay,size: 32.0)
                    // AnimatedIcon:动画图标
                    :AnimatedIcon(icon: AnimatedIcons.play_pause, // 播放到暂停的动画图标
                        //设置图标动画
                        progress: playPauseIconAnimationController,
                    size: 32.0,),
                    onPressed: (){
                      //开始播放或暂停
                      _playPause();
                    },
                  ),
                ),
              ),
            ),
    );
  }
  //开始播放或暂停
  _playPause(){
    //是否播放完
    bool isFinished;
    if(_lastValue.duration != null){
      isFinished = _lastValue.position>= _lastValue.duration;
    }else{
      isFinished = false;
    }
    setState((){
      //如果正在播放
      if(controller.value.isPlaying){
        //方向直行动画 从播放到暂停
        playPauseIconAnimationController.reverse();
        _hideStuff = false;
        _hideTimer?.cancel();
        controller.pause();
      }else{
        _cancelAndREstartTimer();
        if(!controller.value.isInitialized){
          controller.initialize().then((value) => (_){
            controller.play();
            //正向执行动画 从暂停到播放
            playPauseIconAnimationController.forward();
          });
        }else{
          //如果播放完毕 跳转到开始
          if(isFinished){
            controller.seekTo(const Duration());
          }
          //正向执行动画 从暂停到播放
          playPauseIconAnimationController.forward();
          controller.play();
        }
      }
    });
  }
  ///底部控制栏
  AnimatedOpacity _buildBottomBar(context){
    final iconColor = Theme.of(context).textTheme.button.color;
    //使子控件变得透明
    return AnimatedOpacity(
      opacity: _hideStuff?0.0:1.0,
      duration: const Duration(milliseconds: 300),
      child: Container(
        height: barHeight,
        decoration: BoxDecoration(gradient: widget.bottomGradient),
        child: Row(
          children: [
            //暂停和播放icon
            _buildPlayPause(controller),
            //进度条 如果是直播
            if(chewieController.isLive)
             // SizedBox:具有固定宽高的组件,适合控制2个组件之间的空隙
              const SizedBox()
            else
              _buildProgressBar(),
            //播放时间：如果是直播
            if(chewieController.isLive)
              const Expanded(child: Text('LIVE'))
            else//底部控制栏播放时间
              _buildPostion(iconColor),
            //是否显示播放速度设置按钮
            if(chewieController.allowPlaybackSpeedChanging)
              _buildSpeedButton(controller),
            //静音按钮
            if(chewieController.allowMuting)_buildMuteButton(controller),
            //全屏按钮
            if(chewieController.allowFullScreen)_buildExpandButton(),
          ],
        ),
      ),
    );
  }
  //全屏按钮
  _buildExpandButton(){
    return GestureDetector(
      onTap: _onExpandCollapse,
      child: Container(
        height: barHeight,
        padding: const EdgeInsets.only(left: 8.0,right: 8.0),
        child: Center(
          child: Icon(
            chewieController.isFullScreen?Icons.fullscreen_exit_rounded:Icons.fullscreen_rounded,
            color: Colors.white,
          ),
        ),
      ),
    );
  }
  //全屏事件回调方法
  _onExpandCollapse(){
    if(chewieController.videoPlayerController.value.size == null){
      print('_onExpandCollapse:videoPlayerController.value.size is null.');
      return;
    }
    setState((){
      _hideStuff = true;
      //切换全屏
      chewieController.toggleFullScreen();
      _showAfterExpandCollapseTimer = Timer(const Duration(milliseconds: 300), () {
        setState((){
          _cancelAndREstartTimer();
        });
      });
    });
  }
  //底部静音按钮
  _buildMuteButton(VideoPlayerController controller){
    return GestureDetector(
      onTap: (){
        _cancelAndREstartTimer();
        if(_lastValue.volume == 0){
          //打开声音
          controller.setVolume(_lastVolume??0.5);
        }else{
          //关闭声音保存当前值
          _lastVolume = controller.value.volume;
          controller.setVolume(0.0);
        }
      },
      child: Container(
        height: barHeight,
        padding: const EdgeInsets.only(left: 8.0,right: 8.0),
        child: Icon(
          _lastValue != null && _lastValue.volume > 0
              ? Icons.volume_up : Icons.volume_off,
          color: Colors.white,
        ),
      ),
    );
  }
  //底部控制栏播放时间
  _buildPostion(iconColor){
    final postion = _lastValue != null && _lastValue.position != null
        ? _lastValue.position:Duration.zero;
    final duration = _lastValue != null && _lastValue.duration != null
          ? _lastValue.duration:Duration.zero;
    return Padding(padding: EdgeInsets.only(right: 5.0),child: Text(
      "${formatDuration(postion)}/${formatDuration(duration)}",
      style: TextStyle(fontSize: 10,color: Colors.white),
    ),);
  }
  //底部控制栏的暂停和播放按钮
  GestureDetector _buildPlayPause(VideoPlayerController controller){
    return GestureDetector(
      onTap: _playPause,
      child: Container(
        height: barHeight,
        color: Colors.transparent,
        padding: const EdgeInsets.only(
          left: 10.0,
          right: 10.0
        ),
        child: Icon(
          controller.value.isPlaying
              ? Icons.pause_rounded
              : Icons.play_arrow_rounded,
          color: Colors.white,
        ),
      ),
    );
  }
  //底部控制栏的进度条
  _buildProgressBar(){
    return Expanded(child: Padding(
        padding: EdgeInsets.only(right: 15, left: 15),
        child: MaterialVideoProgressBar(
            controller,
            onDragStart:(){
              setState((){
                _dragging = true;
              });
              _hideTimer.cancel();
            },
          onDragEnd:(){
              setState((){
                _dragging = false;
              });
              _startHideTimer();
          },
          colors:chewieController.materialProgressColors??
            ChewieProgressColors(
              playedColor: Theme.of(context).accentColor,
              handleColor: Theme.of(context).accentColor,
              bufferedColor: Theme.of(context).backgroundColor,
              backgroundColor: Theme.of(context).disabledColor
            )

        ),
    ));
  }
  //底部控制栏播放速度按钮
  Widget _buildSpeedButton(controller){
    return GestureDetector(
      onTap: () async{
        _hideTimer?.cancel();
        final chosenSpeed = await showModalBottomSheet(context: context,
          isScrollControlled: true,
        useRootNavigator:  true,
        builder: (context)=>_PalybackSpeedDialog(

        ),
        );
      },
    );
  }

}
class _PalybackSpeedDialog extends StatelessWidget{
  const _PalybackSpeedDialog({
    Key key,
    @required List<double> allowedSpeeds,
    @required  double currentSpeed
}):_allowedSpeeds = allowedSpeeds,
        _currentSpeed = currentSpeed,super(key: key);
  final List<double> _allowedSpeeds;
  final double _currentSpeed;

  @override
  Widget build(BuildContext context) {
    final Color selectedColor = Theme.of(context).primaryColor;
    return ListView.builder(
      // shrinkWrap:决定列表的长度是否仅包裹其内容的长度。true,仅包裹其内容的长度。
      // 当ListView嵌在一个无限长的容器组件中时，shrinkWrap必须为true，否则Flutter会给出警告
      shrinkWrap: true,
      physics: const ScrollPhysics(),
      itemBuilder: (context,index){
        final _speed = _allowedSpeeds[index];
        return ListTile(
          // dense:使文本更小，并将所有内容打包在一起
          dense: true,
          title: Row(
            children: [
              if(_speed == _currentSpeed)
                Icon(Icons.check,size: 20.0,color: selectedColor,)
              else
                Container(width: 20.0),
              const SizedBox(width: 16.0),
              Text(_speed.toString())
            ],
          ),
          selected: _speed == _currentSpeed,
          onTap: (){
            Navigator.of(context).pop(_speed);
          },
        );
      },
      itemCount: _allowedSpeeds.length,
    );
  }
}